<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="150px">
      <el-form-item label="banner图位置" prop="bannerType">
        <el-select v-model="queryParams.bannerType" placeholder="请选择banner图位置" clearable size="small">
          <el-option v-for="dict in bannerTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:banner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:banner:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="Banner位置" align="center" prop="bannerType" :formatter="bannerTypeFormat" width="150"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            @change="handleStateChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="展示顺序" align="center" prop="bannerOrder" />
      <el-table-column label="图片地址">
        <template slot-scope="scope">
          <img :src="scope.row.image" width="100" height="40">
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:banner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:banner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改banner图对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="banner位置" prop="bannerType">
          <el-select v-model="form.bannerType" placeholder="请选择位置">
            <el-option v-for="dict in bannerTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否展示" prop="state">
          <el-select v-model="form.state" placeholder="请选择是否展示">
            <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
          </el-select>
        </el-form-item>

        <el-form-item label="显示排序" prop="bannerOrder">
          <el-input-number v-model="form.bannerOrder" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item prop="image" label="banner">
          <el-upload
            :action="uploadUrls"
            :headers="headers"
            :multiple = true
            list-type="picture-card"
            :with-credentials='true'
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="form.image" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBanner, getBanner, delBanner, addBanner, updateBanner, exportBanner,changeBannerState} from "@/api/manage/banner";
import { getToken } from "@/utils/auth";
const baseUrl = process.env.VUE_APP_BASE_API;

export default {
  name: "Banner",
  data() {
    return {
      bannerTypeOptions:[],
      stateOptions:[{dictValue:0,dictLabel:"不展示"},{dictValue:1,dictLabel:"展示中"}],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // banner图表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerType: undefined,
        state: undefined,
      },
      // 表单参数
      form: {},
      fileList:[],//上传图片数组
      dialogVisible:false,
      uploadUrls: baseUrl + '/common/upload',
      headers: { Authorization: "Bearer " + getToken() },

      // 表单校验
      rules: {
        bannerType:[{required:true,message:"banner图位置不能为空",trigger:"blur"}],
        state:[{required:true,message:"展示状态不能为空",trigger:"blur"}],
        bannerOrder:[{required:true,message:"图片顺序不能为空",trigger:"blur"}],
        image:[{required:true,message:"图片不能为空",trigger:"blur"}],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("banner_type").then(response => {
      this.bannerTypeOptions = response.data;
    });
    console.log("上传图片地址");
    console.log(this.uploadUrls);
  },
  methods: {
    // banner图类型字典翻译
    bannerTypeFormat(row, column) {
      return this.selectDictLabel(this.bannerTypeOptions, row.bannerType);
    },
    stateFormat(row,column){
      return this.selectDictLabel(this.stateOptions, row.state);
    },
    /** 查询banner图列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        bannerType: undefined,
        state: undefined,
        order: undefined,
        image: undefined,
        createTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加banner图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBanner(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改banner图";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除banner图编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBanner(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有banner图数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBanner(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    //修改状态
    handleStateChange(row) {
      let text=row.state === 0 ? "不展示":"展示";
      this.$confirm('确认要' + text + '该banner图吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeBannerState(row.id, row.state);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.state = row.state === 0 ? 1 : 0;
      });
    },

    //图片上传组件
    handleRemove(file, fileList) {//移除
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {//预览
      console.log(file)
      this.form.image = file.url;
      this.dialogVisible = true;
    },
    handleError(err, file, fileList){//上传失败
      console.log(err)
    },
    beforeAvatarUpload(file) {//文件上传之前调用做一些拦截限制
      console.log(file);
      const isJPG = true;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {//图片上传成功
      console.log(res);
      var files = res.url;
      this.fileList.push(files)
      this.form.image = res.url;
    }
  }
};
</script>
